package org.tong.controller;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.tong.bean.Student;

import java.util.Arrays;
import java.util.Date;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/param")
public class ParamController {

    // 1. 无注解获取参数，要求参数名称和HTTP请求参数名称一致，可能为NULL
    @GetMapping("/noAnnotation")
    public String noAnnotation(Integer intVal, Long longVal, String str) {
        return String.format("noAnnotation: intVal:%d, longVal:%d, str:%s", intVal, longVal, str);
    }

    // 2. 使用@RequestParam注解获取参数
    @GetMapping("/requestParam")
    public String requestParam(@RequestParam(name = "int_val", required = true) Integer intVal, @RequestParam(name = "long_val") Long longVal) {
        return String.format("RequestParam:  intVal:%d, longVal:%d", intVal, longVal);
    }

    // 3. 传递数组
    @GetMapping("/arrayParam")
    public String arrayParam(Integer[] intArr) {
        String[] str = new String[1];
        Optional.ofNullable(intArr).ifPresent(array -> {
            str[0] = String.join(",", Arrays.stream(array).map(num -> num.toString()).collect(Collectors.toList()));
        });
        return String.format("arrayParam: %s", str[0]);
    }

    // 4. json参数
    @GetMapping("/jsonParam")
    public String jsonParam(@RequestBody Student student) {
        return String.format("jsonParam: student:%s", student == null ? "null" : student.toString());
    }

    // 5. URL参数
    @GetMapping("/urlParam/{id}/test")
    public String urlParam(@PathVariable(name = "id") Long id) {
        return String.format("urlParam:  id:%d", id);
    }

    // 6. 格式化参数
    @GetMapping("/formatParam")
    public String formatParam(@DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        return String.format("formatParam:  date:%s", date.toString());
    }
}
